﻿using System;
using System.Collections;
using System.Collections.Generic;
using Cinemachine;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;

//Call -> GameFlowManager.Instance.[FunctionName]
public class GameFlowManager : Singleton<GameFlowManager>
{
    [SerializeField]
    private float gameDuration;
    [SerializeField]
    private TextMeshProUGUI clockText;
    [SerializeField]
    private Animator curtainAnimator;
    [SerializeField]
    private CinemachineVirtualCamera camFollow;
    [SerializeField]
    private Transform ITGuyTrans;
    [SerializeField]
    private ITGuy ITGuyscript;
    [SerializeField]
    private GameObject[] disableWhenFinish;
    private bool isGameFinished;
    public bool Won { get; private set; }
    private float timer;
    private bool isITDead;

    public void OnGameLose()
    {
        if (isGameFinished)
            return;
        AudioManager.Instance.PlaySound("GameFail");
        isGameFinished = true;
        isITDead = true;
        Won = false;
        camFollow.Follow = ITGuyTrans;
        camFollow.m_Lens.OrthographicSize = 2.5f;

        ITGuyscript.OnLose();
        NotificationManager.Instance.OnZoomInIT();
        StartCoroutine(CloseCurtainInSeconds());

        for (int i = 0; i < disableWhenFinish.Length; i++)
        {
            disableWhenFinish[i].SetActive(false);
        }
    }

    private IEnumerator CloseCurtainInSeconds()
    {
        yield return new WaitForSeconds(2);
        curtainAnimator.SetTrigger("Close");
        yield return new WaitForSeconds(1);
        NotificationManager.Instance.OnFinish();
    }

    public void OnGameWin()
    {
        AudioManager.Instance.PlaySound("GameWin");
        isGameFinished = true;
        Won = true;
        NotificationManager.Instance.OnZoomInIT();
        NotificationManager.Instance.OnFinish();
        curtainAnimator.SetTrigger("Close");
    }

    public bool CheckIfGameIsFinished()
    {
        return isGameFinished;
    }

    public bool IsITDead()
    {
        return isITDead;
    }

    // Start is called before the first frame update
    void Start()
    {
        timer = gameDuration;
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKey(KeyCode.R) && isGameFinished)
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }
        if (CheckIfGameIsFinished())
        {
            return;
        }

        timer -= Time.deltaTime;
        clockText.text = string.Format("{0}:{1} until off work", (int) timer / 60, ((int) timer % 60).ToString("00"));
        if (timer <= 0)
            OnGameWin();
    }
}